//
//  BaseController.m
//  HB
//
//  Created by 孙智慧 on 16/1/8.
//  Copyright © 2016年 孙智慧. All rights reserved.
//

#import "BaseController.h"
#import "AppDelegate.h"
#import "ZYAudioManager.h"
#import "ZYMusicTool.h"
#import "MusicPlayController.h"

static MusicPlayController *viewController =nil;

@implementation BaseController


-(void) opSuccessForGet:(id)data andFlag:(NSInteger)flag
{
    
}

-(void) opSuccessForGet:(id)data
{}

-(void) opSuccessForDownLoad:(id)data andFlag:(NSString *)flag
{}

-(void) opFail:(NSString *)errorMessage
{}

-(void) opSuccessForPost:(id)data
{}

- (void)networkStateChange
{
    state = [Common checkNetworkState];
}

- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    _hasNextPage=NO;
    
    //网络监测
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    
    self.conn = [Reachability reachabilityForInternetConnection];
    
    [self.conn startNotifier];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self initSqliteDB];
    
    [self setNavBarImage];
    
    [self setNavigationLeft:@"menu" sel:nil];//@selector(openOrCloseLeftList)
    
    [self setNavigationRight:@"playing" sel:@selector(OpenMusic)];
    
    [self setBackBarButton];
    
    //设置后台播放
    [ZYAudioManager initAvAduioSesson];
    
    //设置logo
    [self setNavigationTitleImage:@"hunba"];
    
    //步骤1 设置bar的风格，控制字体颜色
    //self.navigationController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    
    //地理位置
    
    if (IS_IOS8)
    {
        [UIApplication sharedApplication].idleTimerDisabled = TRUE;
        
        locationmanager = [[CLLocationManager alloc] init];
        
        [locationmanager requestAlwaysAuthorization];        //NSLocationAlwaysUsageDescription
        
        [locationmanager requestWhenInUseAuthorization];     //NSLocationWhenInUseDescription
        
        locationmanager.delegate = self;
    }
    
    [self getCity];
    
    self.city =[[NSUserDefaults standardUserDefaults] objectForKey:@"CCLastCity"];
}

-(void)getCity
{
    //__block __weak BaseController *wself = self;
    if (IS_IOS8)
    {
        [[CCLocationManager shareLocation]getCity:^(NSString *cityString) {
            NSLog(@"城市：%@",cityString);
        }];
    }
}


#pragma mark  初始化 sqlite 数据库
-(void) initSqliteDB
{
    _db=[DBHelper sharedMyClass];
    
}

-(MusicPlayController *) musicPlay
{
    if(viewController==nil)
    {
        viewController= [self.storyboard instantiateViewControllerWithIdentifier:@"playView"];
        
        [viewController setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    }
    return viewController;
}

#pragma mark  打开左侧菜单栏
//- (void) openOrCloseLeftList
//{
//    AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//
//    if (tempAppDelegate.LeftSlideVC.closed)
//    {
//        [tempAppDelegate.LeftSlideVC openLeftView];
//    }
//    else
//    {
//        [tempAppDelegate.LeftSlideVC closeLeftView];
//    }
//
//}

#pragma mark 顶栏右边按钮
- (void)OpenMusic
{
    if([self musicPlay]!=nil && ([self musicPlay].isRoationing || [self musicPlay].playingMusic!=nil))
    {
        [self.view.window.rootViewController presentViewController:[self musicPlay] animated:true completion:nil];
    }
}

#pragma mark 开始滚动
- (void) startRoating:(UIView *) _view  animationKey:(NSString *)key
{
    
    CABasicAnimation *animation=[CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    animation.fromValue= [NSNumber numberWithFloat:0.0];
    animation.toValue=[NSNumber numberWithFloat:M_PI*2];
    animation.repeatCount= MAXFLOAT;
    animation.duration = 20.0;
    animation.removedOnCompletion=NO;
    [_view.layer addAnimation:animation forKey:key];
    
}

#pragma mark 暂停滚动
- (void) pasumeRoation:(UIView *) _view
{
    CFTimeInterval pasueTime=  [_view.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    _view.layer.speed = 0.0;
    _view.layer.timeOffset= pasueTime;
}

#pragma mark 恢复滚动
- (void) resmeRoation:(UIView *) _view
{
    CFTimeInterval pausedTime = _view.layer.timeOffset;
    _view.layer.speed=1.0;
    _view.layer.timeOffset=0.0;
    _view.layer.beginTime=0.0;
    CFTimeInterval timeSpan=[_view.layer convertTime:CACurrentMediaTime() fromLayer:nil]- pausedTime;
    _view.layer.beginTime=timeSpan;
}


-(void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //设置导航栏不隐藏
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

#pragma mark 设置自定义按钮
- (UIButton *)customButton:(NSString *)imageName
                  selector:(SEL)sel
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    btn.frame = CGRectMake(0, 0, 22, 22);
    
    [btn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    
    [btn addTarget:self action:sel forControlEvents:UIControlEventTouchUpInside];
    
    return btn;
}

#pragma mark 设置左侧按钮
- (void)setNavigationLeft:(NSString *)imageName sel:(SEL)sel
{
    //    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:[self customButton:imageName selector:sel]];
    //
    //    self.navigationItem.leftBarButtonItem = item;
}

#pragma mark 设置右侧按钮
- (void)setNavigationRight:(NSString *)imageName sel:(SEL)sel
{
    UIButton *btn=[self customButton:imageName selector:sel];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.rightBarButtonItem = item;
}

//设置状态栏颜色 在Nav控件中不起作用
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

//设置导航栏按钮
-(void) setBackBarButton
{
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
    self.navigationItem.backBarButtonItem = item;
}

//设置导航栏中心图
- (void)setNavigationTitleImage:(NSString *)imageName
{
    UIImage *image = [UIImage imageNamed:imageName];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    imageView.contentMode= UIViewContentModeScaleAspectFit;
    self.navigationItem.titleView = imageView;
}

- (void)setNavBarImage
{
    UIImage *image = [UIImage imageNamed:@"NavigationBar44.png"];
    [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    NSDictionary *attribute = @{
                                NSForegroundColorAttributeName:[UIColor whiteColor],
                                NSFontAttributeName:[UIFont systemFontOfSize:18]
                                };
    [self.navigationController.navigationBar setTitleTextAttributes:attribute];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    if(viewController.isRoationing)
    {
        UIBarButtonItem *item =  self.navigationItem.rightBarButtonItem;
        
        UIButton *btn= (UIButton *) item.customView;
        
        if(btn.tag == 0)
        {
            [btn.layer removeAllAnimations];
            
            btn.tag=1;
            
            [self startRoating:btn animationKey:@"btnRoation"];
        }
    }
}

-(void) stopNavRightBtnRoation
{
    UIBarButtonItem *item =  self.navigationItem.rightBarButtonItem;
    
    UIButton *btn= (UIButton *) item.customView;
    
    btn.tag=0;
    
    [btn.layer removeAnimationForKey:@"btnRoation"];
}

-(void)dealloc
{
    RemoveNofify;
}

-(void) waitingFor:(NSString *)labelText andMethod:(SEL)method onTarget:(id)target
{
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    
    [self.view addSubview:HUD];
    
    HUD.delegate = target;
    
    HUD.labelText = labelText;
    
    [HUD showWhileExecuting:method onTarget:target withObject:nil animated:YES];

}

-(void)addViewRes:(ZYMusic *) music
{
    
    [_db addViewResourse:music];
    
}

@end
